package edu.msg.hrappy.web.servlet;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.ejb.EJB;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.msg.hrappy.backend.model.Candidate;
import edu.msg.hrappy.backend.service.CandidateService;
import edu.msg.hrappy.backend.service.JobService;
import edu.msg.hrappy.backend.service.UserService;

/**
 * Servlet implementation class AddCandidateServlet
 */

public class DownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@EJB
	private CandidateService candidateService;
	@EJB
	private UserService userService;
	@EJB
	private JobService jobService;

	private static final int BUFFER_SIZE = 4096;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DownloadServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		try {

			Long id = 1L;
			id = Long.parseLong((String) request.getParameter("id"));
			Candidate candidate = candidateService.getById(id);
			InputStream inputStream = new ByteArrayInputStream(
					candidate.getCv());
			int fileLength = inputStream.available();

			ServletContext context = getServletContext();
			String fileName = candidate.getFileName();

			String mimeType = context.getMimeType(fileName);
			if (mimeType == null) {
				mimeType = "application/octet-stream";
			}

			response.setContentType(mimeType);
			response.setContentLength(fileLength);
			String headerKey = "Content-Disposition";
			String headerValue = String.format("attachment; filename=\"%s\"",
					fileName);
			response.setHeader(headerKey, headerValue);

			OutputStream outStream = response.getOutputStream();

			byte[] buffer = new byte[BUFFER_SIZE];
			int bytesRead = -1;

			while ((bytesRead = inputStream.read(buffer)) != -1) {
				outStream.write(buffer, 0, bytesRead);
			}

			inputStream.close();
			outStream.close();

		} catch (IOException ex) {
			response.getWriter().print("IO Error: " + ex.getMessage());
		} finally {
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

}
